/**
 * Copyright © 2016-2022 The Thingsboard Authors
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.thingsboard.server.dao.model.sql;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.thingsboard.server.common.data.IotConfig;
import org.thingsboard.server.common.data.id.IotConfigId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.dao.model.BaseSqlEntity;
import org.thingsboard.server.dao.model.ModelConstants;
import org.thingsboard.server.dao.model.SearchTextEntity;
import org.thingsboard.server.dao.util.mapping.JsonStringType;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.UUID;

@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@TypeDef(name = "json", typeClass = JsonStringType.class)
@Table(name = "iot_config")
public class IotConfigEntity extends BaseSqlEntity<IotConfig> implements SearchTextEntity<IotConfig> {

    @Column(name = ModelConstants.TENANT_ID_PROPERTY)
    private UUID tenantId;

    @Column(name = ModelConstants.TITLE_PROPERTY)
    private String title;

    @Column(name = ModelConstants.SEARCH_TEXT_PROPERTY)
    private String searchText;

    @Type(type = "json")
    @Column(name = ModelConstants.ADDITIONAL_INFO_PROPERTY)
    private JsonNode additionalInfo;

    public IotConfigEntity() {
        super();
    }

    public IotConfigEntity(IotConfig iotConfig) {
        if (iotConfig.getId() != null) {
            this.setUuid(iotConfig.getId().getId());
        }
        this.setCreatedTime(iotConfig.getCreatedTime());
        this.tenantId = iotConfig.getTenantId().getId();
        this.title = iotConfig.getTitle();
        this.additionalInfo = iotConfig.getAdditionalInfo();
    }

    @Override
    public String getSearchTextSource() {
        return title;
    }

    @Override
    public void setSearchText(String searchText) {
        this.searchText = searchText;
    }

    @Override
    public IotConfig toData() {
        IotConfig iotConfig = new IotConfig(new IotConfigId(this.getUuid()));
        iotConfig.setCreatedTime(createdTime);
        iotConfig.setTenantId(TenantId.fromUUID(tenantId));
        iotConfig.setTitle(title);
        iotConfig.setAdditionalInfo(additionalInfo);
        return iotConfig;
    }
}
